package com.sxran.im.handler;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sxran.im.bean.NotificationBody;
import com.sxran.im.controller.ImController;
import com.sxran.im.dao.ImChatBodyMapper;
import com.sxran.im.info.ImChatBody;
import com.sxran.im.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class RevokeMessageCmdHandler extends AbstractCmdHandler<ImChatBody>{
    @Resource
    private ImChatBodyMapper imChatBodyMapper;
    @Resource
    private UserGroupService userGroupService;
    @Override
    public Object doBeanService(ImChatBody json) {
        // 对消息表的消息整体设置状态。
        ImChatBody imChatBody = imChatBodyMapper.selectById(json.getId());
        String extras0 = imChatBody.getExtras0();
        JSONObject jsonObject = JSONObject.parseObject(extras0);
        jsonObject.put("isRevoke",1);
        imChatBody.setExtras0(jsonObject.toJSONString());
        imChatBodyMapper.updateById(imChatBody);
        // 通知其他人，将消息实时的撤回。

        String groupId = imChatBody.getGroupId();
        String[] targetList = null;
        if (StrUtil.isBlank(groupId)) {
            targetList = new String[]{
                    imChatBody.getToId(),
                    imChatBody.getFromId()
            };
        }else{
            List<String> userIds = userGroupService.getUserIds(groupId);
            targetList = ArrayUtil.toArray(userIds,String.class);
        }
        NotificationBody notificationBody = new NotificationBody();
        notificationBody.setTargetList(targetList);
        notificationBody.setContent("[此消息已被撤回]");
        // 将群组id放入到扩展字段中。
        JSONObject extras = notificationBody.getExtras();
        extras.put("conversation",imChatBody.getConversation());
        extras.put("messageId",imChatBody.getId());
        return notificationBody;
    }



}
